/*
 * @(#)GuiceInterceptor.java   08/12/24
 *
 *
 */



package net.learntechnology.examples.ext.stripes;

//~--- non-JDK imports --------------------------------------------------------

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;

import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.config.ConfigurableComponent;
import net.sourceforge.stripes.config.Configuration;
import net.sourceforge.stripes.controller.ExecutionContext;
import net.sourceforge.stripes.controller.Interceptor;
import net.sourceforge.stripes.controller.Intercepts;
import net.sourceforge.stripes.controller.LifecycleStage;

//~--- JDK imports ------------------------------------------------------------

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author nmaves
 */
@Intercepts(LifecycleStage.ActionBeanResolution)
public class GuiceInterceptor implements Interceptor, ConfigurableComponent {
	public static final String MODULES = "Guice.Modules";
	private static final Log   log     = LogFactory.getLog(GuiceInterceptor.class);
	private static Injector    injector;

	public void init(Configuration config) throws Exception {
		List<Class<? extends Module>> moduleClasses =
			config.getBootstrapPropertyResolver().getClassPropertyList(MODULES, Module.class);
		int size = moduleClasses.size();

		if (size > 0) {
			List<Module> modules = new ArrayList<Module>(size);

			for (Class<? extends Module> cls : moduleClasses) {
				modules.add(cls.newInstance());
			}

			injector = Guice.createInjector(modules);
			log.info("Created Guice injector with modules: " + moduleClasses);
		} else {
			injector = Guice.createInjector();
		}
	}

	public Resolution intercept(ExecutionContext context) throws Exception {
		injector.injectMembers(context.getActionBeanContext());

		Resolution resolution = context.proceed();

		injector.injectMembers(context.getActionBean());

		return resolution;
	}

	public static Injector getInjector() {
		return injector;
	}
}
